const fs = require('fs');
const http = require('http');
const path = require('path');
import request from 'umi-request'//可用axios等代替
import {app, ipcMain} from 'electron'
import {win} from "@/background";

let remoteUrl = process.env.NODE_ENV === 'development'?'http://49.7.223.79:23888/': 'http://49.7.223.79:23888/'
let remoteMediaUrl=`${remoteUrl}api/appliedModule/page?pageNum=1&pageSize=10&bizId=262&searchSource=0`
let completeCount = 0
let remoteData = []

//1. 先通过本地和远程对比，删除本地有而远程没有的多余文件
//2. 再循环获取远程文件大小，找出本地大小与远程文件大小不一致的文件，进行删除
//3. 然后再重新下载之前被删除的文件，如果断网，则直接删除
//4. 下载完成后进行比对，如果本地文件和远程文件的名称和大小全部一致，则认为是同一个文件，直到全部比对成功，则认为本地与远程完全一样，发送完全一样的通知消息
//5. 本地刷新
ipcMain.on('startDownload', async () => {
    console.log('开始下载');
    let downloadDirectory = getLicensePath()//本地静态路径
    let localMediaFileList = getLocalMediaFileList(downloadDirectory)//本地已有媒体文件
    remoteData = []
    try {
        let res = await request.get(remoteMediaUrl)
        if (res.success) {
            console.log('开始下载1');
            //console.log('当前已经下载的视频', localMediaFileList);
            remoteData = res.data.records
            //格式化远程文件,只拉取名字
            let remoteFileList = getRemoteFileNameList(res.data.records)
            //console.log('远程所有文件名', remoteFileList);
            if (remoteFileList.length > 0) {
                let shouldBeDelete = findShouldDeleteFileList(localMediaFileList, remoteFileList);//将本地和远程进行对比，删除本地多出来的文件
                shouldBeDelete.forEach((s) => {
                    const filePath = path.join(downloadDirectory, s);
                    errTryCatchFsUnlink(filePath,'本地多余文件')
                });
            }

            //将远程文件名挨个在本地查找
            for (let i = 0; i < remoteData.length; i++) {
                let fileName = ''
                /**------根据后台返回的数据，所做的定制化处理，根据需要进行修改------**/
                if (remoteData[i].img) {
                    fileName = remoteData[i].img.split('/').pop()
                } else if (remoteData[i].video) {
                    fileName = remoteData[i].video.split('/').pop()
                }
                /**------定制化逻辑结束------**/
                let filePath = path.join(downloadDirectory, fileName)
                let mediaUrl = `${remoteUrl}upPath/PRODUCT/${fileName.endsWith('.mp4') ? 'video' : 'pic'}/${fileName}`;
                let req = http.get(mediaUrl, (response) => {
                    if (fs.existsSync(filePath)) {//如果本地存在这个文件，但大小和远程不一致，则删除本地文件
                        let localSize = (fs.statSync(filePath).size).toString()
                        let remoteSize = response.headers['content-length']
                        if (localSize !== remoteSize) {
                            win.webContents.send('sameNameNotSameSize', `${filePath}本地${localSize}，远程${remoteSize}`)
                            errTryCatchFsUnlink(filePath,'本地和远程大小不一时')
                        } else {////如果本地存在这个文件，大小和远程一致，则标记已下载完成加1
                            completeCount++
                            if(completeCount === remoteData.length){//当标记已下载数量等于远程文件数量时，则发送本地与远程媒体完全相等的通知
                                win.webContents.send('allTheSame', remoteData)
                                completeCount=0
                            }
                            req.destroy()
                        }
                    }
                    if (!fs.existsSync(filePath)) {//文件不存在
                        win.webContents.send('willDownload2', remoteData)
                        const file = fs.createWriteStream(filePath);
                        response.pipe(file);
                        file.on('finish', () => {
                            req.destroy()//关闭连接
                            if (!req.aborted) {//如果是断网或者网络连接超时的情况，则不计入已下载的文件列表
                                file.close();
                                completeCount++
                                if(completeCount === remoteData.length){
                                    win.webContents.send('allTheSame', remoteData)
                                    completeCount=0
                                }
                                req.destroy()
                            }
                        });
                    }
                })
                req.setTimeout(10000, () => {
                    win.webContents.send('netWorkTimeOut', '请求超时,未下载完成的文件进行删除' + filePath)
                    req.aborted = true//添加断网超时标记
                    req.destroy()
                    errTryCatchFsUnlink(filePath,'网络超时')
                })
                req.on('error', () => {//一般不会走到这里来
                    errTryCatchFsUnlink(filePath,'网络错误')
                    req.destroy()
                });
            }
        }
    } catch (e) {
        console.log('失败了',e);
        //没网就将本地的文件名传递过去
        win.webContents.send('netWorkError', getLocalData(localMediaFileList))
    }
})

function errTryCatchFsUnlink(filePath,message){
    try {
        fs.access(filePath,fs.constants.W_OK,(err)=>{
            if(err){
                win.webContents.send('mainProcessError', `mainProcessError:${message}删除文件失败:${filePath}`)
            }else{
                fs.unlinkSync(filePath);
            }
        })
    }catch (e) {
        win.webContents.send('mainProcessError', `mainProcessError:${message}删除文件失败:${filePath}`)
    }
}
//没有网路时，只加载本地
function getLocalData(fileNameList){
   return fileNameList.map((s,i)=>{
       return {
           id:i,
           timer:s.endsWith('.mp4')?'0.5':'5',
           finallyUrl:`local-video://media/${s}`,
           type:s.endsWith('.mp4')?'mp4':'image'
       }
    })
}

//组装自己的数据格式，以后台应用配置为准
function getLocalMediaFileList(dir) {
    return fs.readdirSync(dir).filter(file => {
        const extension = path.extname(file).toLowerCase();
        return ['.mp4', '.png', '.jpg'].includes(extension);
    })
}
//获取远程文件名
function getRemoteFileNameList(data) {
    return data.map((s) => {
        const tempArr = s.video ? s.video.split('/') : s.img ? s.img.split('/') : [];
        return tempArr[tempArr.length - 1];
    });
}


//检测本地文件与远程文件有哪些不一样，多余的进行删除
function findShouldDeleteFileList(a, b) {
    const missingElements = [];
    for (let i = 0; i < a.length; i++) {
        if (!b.includes(a[i])) {
            missingElements.push(a[i]);
        }
    }
    return missingElements;
}

//获取本地资源路径
function getLicensePath() {
    let exePath = app.getAppPath();
    let filePath
    if (process.env.NODE_ENV === 'development') {
        filePath = exePath.substring(0, (exePath.length - 13)) + 'public\\media'
    } else {
        filePath = exePath + '\\media'
    }
    return filePath
}